<template>
  <div class="book-borrow" v-if="currentUser">
    <div class="header">
      <h2>图书借阅</h2>
      <div class="header-info">
        <el-tag type="info">当前用户：{{ currentUser.realName || currentUser.username }}</el-tag>
        <!-- 普通用户显示我的借阅记录按钮 -->
        <el-button 
          v-if="!isAdmin()" 
          type="primary" 
          @click="showMyBorrows" 
          style="margin-left: 10px">
          我的借阅记录
        </el-button>
      </div>
    </div>

    <!-- 我的借阅记录对话框 -->
    <el-dialog
      v-model="myBorrowsDialog.visible"
      title="我的借阅记录"
      width="80%"
      @close="myBorrowsDialog.visible = false"
    >
      <el-table
        :data="myBorrowsList"
        v-loading="myBorrowsDialog.loading"
        style="width: 100%"
        border
      >
        <el-table-column prop="isbn" label="ISBN" width="150" />
        <el-table-column prop="title" label="图书名称" min-width="200" />
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="borrowDate" label="借阅日期" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.borrowDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="returnDate" label="应还日期" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.returnDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="actualReturnDate" label="实际归还日期" width="160">
          <template #default="{ row }">
            {{ row.actualReturnDate ? formatDateTime(row.actualReturnDate) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" width="150" show-overflow-tooltip />
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination" style="margin-top: 20px; text-align: center;">
        <el-pagination
          v-model:current-page="myBorrowsPagination.current"
          v-model:page-size="myBorrowsPagination.size"
          :page-sizes="[5, 10, 20, 50]"
          :total="myBorrowsPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleMyBorrowsSizeChange"
          @current-change="handleMyBorrowsCurrentChange"
        />
      </div>
    </el-dialog>

    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :model="searchForm" inline>
        <el-form-item label="搜索">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入书名、作者、ISBN、出版社"
            style="width: 300px"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable style="width: 150px">
            <el-option label="计算机" value="计算机" />
            <el-option label="文学" value="文学" />
            <el-option label="历史" value="历史" />
            <el-option label="科学" value="科学" />
            <el-option label="艺术" value="艺术" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="可借" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 图书列表 -->
    <div class="book-grid">
      <el-row :gutter="20">
        <el-col 
          v-for="book in bookList" 
          :key="book.id" 
          :xs="24" 
          :sm="12" 
          :md="8" 
          :lg="6" 
          :xl="4"
        >
          <el-card class="book-card" :body-style="{ padding: '0px' }">
            <div class="book-cover">
              <div class="cover-placeholder">
                <el-icon size="40" color="#909399">
                  <Document />
                </el-icon>
                <div class="book-title">{{ book.title }}</div>
              </div>
            </div>
            <div class="book-info">
              <h3 class="book-title" :title="book.title">{{ book.title }}</h3>
              <p class="book-author">作者：{{ book.author }}</p>
              <p class="book-publisher">出版社：{{ book.publisher }}</p>
              <p class="book-isbn">ISBN：{{ book.isbn }}</p>
              <p class="book-category">分类：{{ book.category || '未分类' }}</p>
              <p class="book-location">位置：{{ book.location || '未知' }}</p>
              <div class="book-status">
                <el-tag :type="book.status === 1 ? 'success' : 'danger'">
                  {{ book.status === 1 ? '可借' : '下架' }}
                </el-tag>
                <el-tag type="info" style="margin-left: 8px">
                  可借：{{ book.availableCopies }}/{{ book.totalCopies }}
                </el-tag>
              </div>
              <div class="book-actions">
                <el-button 
                  type="primary" 
                  size="small" 
                  :disabled="book.status !== 1 || book.availableCopies <= 0"
                  @click="handleBorrow(book)"
                >
                  {{ book.availableCopies > 0 ? '借阅' : '无库存' }}
                </el-button>
                <el-button 
                  size="small" 
                  @click="handleViewDetail(book)"
                >
                  详情
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :page-sizes="[12, 24, 48, 96]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 借阅对话框 -->
    <el-dialog
      v-model="borrowDialog.visible"
      title="借阅图书"
      width="500px"
      @close="resetBorrowForm"
    >
      <el-form
        ref="borrowFormRef"
        :model="borrowForm"
        :rules="borrowRules"
        label-width="100px"
      >
        <el-form-item label="图书名称">
          <span>{{ borrowForm.bookTitle }}</span>
        </el-form-item>
        <el-form-item label="作者">
          <span>{{ borrowForm.author }}</span>
        </el-form-item>
        <el-form-item label="ISBN">
          <span>{{ borrowForm.isbn }}</span>
        </el-form-item>
        <el-form-item label="借阅天数" prop="borrowDays">
          <el-input-number
            v-model="borrowForm.borrowDays"
            :min="1"
            :max="90"
            style="width: 100%"
          />
          <div class="form-tip">借阅天数范围：1-90天</div>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="borrowForm.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="borrowDialog.visible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleBorrowSubmit"
            :loading="borrowDialog.loading"
          >
            确认借阅
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图书详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      title="图书详情"
      width="600px"
    >
      <div class="book-detail" v-if="detailDialog.book">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="图书名称">{{ detailDialog.book.title }}</el-descriptions-item>
          <el-descriptions-item label="作者">{{ detailDialog.book.author }}</el-descriptions-item>
          <el-descriptions-item label="ISBN">{{ detailDialog.book.isbn }}</el-descriptions-item>
          <el-descriptions-item label="出版社">{{ detailDialog.book.publisher }}</el-descriptions-item>
          <el-descriptions-item label="分类">{{ detailDialog.book.category || '未分类' }}</el-descriptions-item>
          <el-descriptions-item label="位置">{{ detailDialog.book.location || '未知' }}</el-descriptions-item>
          <el-descriptions-item label="总数量">{{ detailDialog.book.totalCopies }}</el-descriptions-item>
          <el-descriptions-item label="可借数量">{{ detailDialog.book.availableCopies }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="detailDialog.book.status === 1 ? 'success' : 'danger'">
              {{ detailDialog.book.status === 1 ? '可借' : '下架' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(detailDialog.book.createTime) }}</el-descriptions-item>
        </el-descriptions>
        <div class="book-description" v-if="detailDialog.book.description">
          <h4>图书简介：</h4>
          <p>{{ detailDialog.book.description }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
  
  <!-- 加载状态 -->
  <div v-else class="loading-container">
    <el-loading-component />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Document } from '@element-plus/icons-vue'
import { getBookList } from '@/api/book'
import { borrowBook, getBorrowByUserId } from '@/api/borrow'
import { useUserStore } from '@/store/user'

// 用户状态
const userStore = useUserStore()
const currentUser = computed(() => userStore.userInfo || null)

// 判断是否为管理员
const isAdmin = () => {
  return userStore.isAdmin()
}

// 搜索表单
const searchForm = reactive({
  keyword: '',
  category: '',
  status: ''
})

// 分页
const pagination = reactive({
  current: 1,
  size: 12,
  total: 0
})

// 图书列表
const bookList = ref([])
const loading = ref(false)

// 借阅对话框
const borrowDialog = reactive({
  visible: false,
  loading: false
})

const borrowForm = reactive({
  bookId: null,
  bookTitle: '',
  author: '',
  isbn: '',
  borrowDays: 30,
  remarks: ''
})

const borrowRules = {
  borrowDays: [
    { required: true, message: '请输入借阅天数', trigger: 'blur' },
    { type: 'number', min: 1, max: 90, message: '借阅天数必须在1-90天之间', trigger: 'blur' }
  ]
}

const borrowFormRef = ref()

// 详情对话框
const detailDialog = reactive({
  visible: false,
  book: null
})

// 我的借阅记录对话框
const myBorrowsDialog = reactive({
  visible: false,
  loading: false
})

const myBorrowsList = ref([])
const myBorrowsPagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 组件是否已卸载的标志
let isComponentMounted = true

// 获取图书列表
const fetchBookList = async () => {
  if (!isComponentMounted) return
  
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      size: pagination.size,
      keyword: searchForm.keyword || undefined,
      category: searchForm.category || undefined,
      status: searchForm.status !== '' ? searchForm.status : undefined
    }
    
    const response = await getBookList(params)
    if (response.code === 200 && isComponentMounted) {
      bookList.value = response.data.records
      pagination.total = response.data.total
    } else if (isComponentMounted) {
      ElMessage.error(response.message || '获取图书列表失败')
    }
  } catch (error) {
    if (isComponentMounted) {
      console.error('获取图书列表失败:', error)
      ElMessage.error('获取图书列表失败')
    }
  } finally {
    if (isComponentMounted) {
      loading.value = false
    }
  }
}

// 获取我的借阅记录
const fetchMyBorrows = async () => {
  if (!isComponentMounted) return
  
  if (!currentUser.value || !currentUser.value.id) {
    ElMessage.error('请先登录')
    return
  }
  
  myBorrowsDialog.loading = true
  try {
    const params = {
      page: myBorrowsPagination.current,
      size: myBorrowsPagination.size
    }
    
    const response = await getBorrowByUserId(currentUser.value.id, params)
    if (response.code === 200 && isComponentMounted) {
      myBorrowsList.value = response.data.records
      myBorrowsPagination.total = response.data.total
    } else if (isComponentMounted) {
      ElMessage.error(response.message || '获取借阅记录失败')
    }
  } catch (error) {
    if (isComponentMounted) {
      console.error('获取借阅记录失败:', error)
      ElMessage.error('获取借阅记录失败')
    }
  } finally {
    if (isComponentMounted) {
      myBorrowsDialog.loading = false
    }
  }
}

// 显示我的借阅记录
const showMyBorrows = () => {
  myBorrowsDialog.visible = true
  myBorrowsPagination.current = 1
  fetchMyBorrows()
}

// 我的借阅记录分页处理
const handleMyBorrowsSizeChange = (size) => {
  myBorrowsPagination.size = size
  myBorrowsPagination.current = 1
  fetchMyBorrows()
}

const handleMyBorrowsCurrentChange = (current) => {
  myBorrowsPagination.current = current
  fetchMyBorrows()
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchBookList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    keyword: '',
    category: '',
    status: ''
  })
  pagination.current = 1
  fetchBookList()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  fetchBookList()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  fetchBookList()
}

// 借阅图书
const handleBorrow = (book) => {
  if (!currentUser.value || !currentUser.value.id) {
    ElMessage.error('请先登录')
    return
  }
  
  if (book.availableCopies <= 0) {
    ElMessage.warning('该图书暂无库存')
    return
  }
  
  Object.assign(borrowForm, {
    bookId: book.id,
    bookTitle: book.title,
    author: book.author,
    isbn: book.isbn,
    borrowDays: 30,
    remarks: ''
  })
  
  borrowDialog.visible = true
}

// 提交借阅
const handleBorrowSubmit = async () => {
  if (!borrowFormRef.value) return
  
  if (!currentUser.value || !currentUser.value.id) {
    ElMessage.error('请先登录')
    return
  }
  
  try {
    await borrowFormRef.value.validate()
  } catch (error) {
    return
  }
  
  borrowDialog.loading = true
  try {
    const params = {
      userId: currentUser.value.id,
      bookId: borrowForm.bookId,
      borrowDays: borrowForm.borrowDays,
      remarks: borrowForm.remarks
    }
    
    const response = await borrowBook(params)
    if (response.code === 200 && isComponentMounted) {
      ElMessage.success('借阅成功！')
      borrowDialog.visible = false
      fetchBookList() // 刷新图书列表
    } else if (isComponentMounted) {
      ElMessage.error(response.message || '借阅失败')
    }
  } catch (error) {
    if (isComponentMounted) {
      console.error('借阅失败:', error)
      ElMessage.error('借阅失败')
    }
  } finally {
    if (isComponentMounted) {
      borrowDialog.loading = false
    }
  }
}

// 重置借阅表单
const resetBorrowForm = () => {
  Object.assign(borrowForm, {
    bookId: null,
    bookTitle: '',
    author: '',
    isbn: '',
    borrowDays: 30,
    remarks: ''
  })
  if (borrowFormRef.value) {
    borrowFormRef.value.resetFields()
  }
}

// 查看图书详情
const handleViewDetail = (book) => {
  detailDialog.book = book
  detailDialog.visible = true
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    1: 'success', // 借阅中
    2: 'info',    // 已归还
    3: 'warning', // 逾期
    4: 'danger'   // 丢失
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '借阅中',
    2: '已归还',
    3: '逾期',
    4: '丢失'
  }
  return statusMap[status] || '未知'
}

// 页面加载时获取数据
onMounted(() => {
  fetchBookList()
})

// 组件卸载时的清理逻辑
onUnmounted(() => {
  isComponentMounted = false
})
</script>

<style scoped>
.book-borrow {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.search-bar {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.book-grid {
  margin-bottom: 20px;
}

.book-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  cursor: pointer;
}

.book-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.book-cover {
  height: 200px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.cover-placeholder {
  text-align: center;
}

.cover-placeholder .book-title {
  margin-top: 10px;
  font-size: 14px;
  line-height: 1.4;
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.book-info {
  padding: 15px;
}

.book-info .book-title {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.book-info p {
  margin: 5px 0;
  font-size: 12px;
  color: #606266;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.book-status {
  margin: 10px 0;
}

.book-actions {
  display: flex;
  gap: 8px;
  margin-top: 10px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.book-detail {
  padding: 10px 0;
}

.book-description {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.book-description h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.book-description p {
  margin: 0;
  line-height: 1.6;
  color: #606266;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}
</style> 